package com.h2cloud.workflow;

import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.*;

@Slf4j
public class MonitorTreadPoolExecutor extends ThreadPoolExecutor {

    public MonitorTreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }

    public MonitorTreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    public MonitorTreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
    }

    public MonitorTreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    @Override
    public void shutdown() {
        super.shutdown();
    }

    @Override
    public List<Runnable> shutdownNow() {
        return super.shutdownNow();
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
//        log.debug("afterExecute...");
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        log.debug("isThrowable?:{}", (t == null));
//        log.debug("isTrue?:{}", (r instanceof Future<?>));
//        log.debug("isTrue?:{}", r);
        super.afterExecute(r, t);
        if (t == null && r instanceof Future<?>) {
            try {
                //获取线程执行结果
                Object result = ((Future<?>) r).get();
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt(); // ignore/reset
            }
        }
        if (t != null) {
            //处理异常
            log.error("detailMessage:{}, poolSize:{}, activeCount:{}, queueSize:{}", t.getMessage(), this.getPoolSize(), this.getActiveCount(), this.getQueue().size());
        }
        //记录线程执行时间
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        log.debug("name:{}, poolSize:{}, activeCount:{}, queueSize:{}", t.getName(), this.getPoolSize(), this.getActiveCount(), this.getQueue().size());
        super.beforeExecute(t, r);
    }

}

